package comp.wxapi.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 文件相关的stroage服务工具类
 * @author Administrator
 */
public class StorageServiceUtils {
	
	private static final String STORAGE_URL = "/storage/presignedGetObject?objectName=";
	
	private static final Logger logger = LoggerFactory.getLogger(StorageServiceUtils.class);
	
	/**
	 * 获取ApiClientCert证书路径
	 * @param fileNo
	 * @param host
	 * @return
	 */
	public static String getApiClientCertPath(String storeFileName,String host) {
		String keyPath = "";
		storeFileName = getStoreFileName(storeFileName);
		FileOutputStream fos = null;
		try {
			String path = "";
			if(storeFileName.endsWith(".p12")) {
				path = new File("").getCanonicalPath()+File.separator+storeFileName;
			}else {
				path = new File("").getCanonicalPath()+File.separator+storeFileName+".p12";
			}
			File file = new File(path);
			if(!file.exists()) {
				String downloadURL = getDownloadURL(host,storeFileName);
				logger.info("=====file download URI=====\n"+downloadURL);
				logger.info("==========文件下载开始==========");
				Long start = System.currentTimeMillis();
//				URL url = new URL(downloadURL);  
//	            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();    
//	            httpUrlConn.setDoOutput(true);
//	            httpUrlConn.setDoInput(true);  
//	            httpUrlConn.setUseCaches(false);
//	            httpUrlConn.setRequestMethod("GET");
//	            InputStream inputStream = httpUrlConn.getInputStream();
	            BufferedInputStream bis = new BufferedInputStream(RequestUtils.get(downloadURL, null).byteStream());
	            
	            fos = new FileOutputStream(file);
	            int b = 0;
	            byte[] byArr = new byte[1024*4];
	            while ((b=bis.read(byArr))!=-1) {  
	            	fos.write(byArr, 0, b);
	            }
	            logger.info("==========文件下载结束,用时：{}ms==========",(System.currentTimeMillis()-start));
			}
            keyPath = path;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("证书下载出错。。。。");
		}finally {
			if(fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		logger.info("=====key path=====\n"+keyPath);
		return keyPath;
	}
	
	/**
	 * 文件编号解析
	 * @param fileNo
	 * @return
	 */
	public static String getStoreFileName(String value) {
		try {
			List<JSONObject> jsonObjects = JSON.parseArray(value, JSONObject.class);
			if(jsonObjects != null && jsonObjects.size()>0) {
				JSONObject jsonObject = jsonObjects.get(0);
				return jsonObject.getString("storeFileName");
			}
			return "";
		} catch (Exception e) {
			return value;
		}
	}
	
	/**
	 * 从minio服务器获取文件下载路径
	 * @param fileNo
	 * @return
	 */
	public static String getDownloadURL(String host,String storeFileName) throws Exception {
		String requestURL = host+STORAGE_URL+storeFileName;
		String response = RequestUtils.get(requestURL, null).string();
		logger.info("=====download response data=====\n"+response);
		return response;
	}
	
	/**
	 * 从minio服务器获取文件输入流
	 * @param value
	 * @param host
	 * @return
	 */
	public static InputStream getFileInputStream(String downloadURL) {
		try {
//			URL url = new URL(downloadURL);  
//	        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();    
//	        httpUrlConn.setDoOutput(true);
//	        httpUrlConn.setDoInput(true);  
//	        httpUrlConn.setUseCaches(false);
//	        httpUrlConn.setRequestMethod("GET");
//	        InputStream inputStream = httpUrlConn.getInputStream();
			InputStream inputStream = RequestUtils.get(downloadURL, null).byteStream();
	        return inputStream;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 从minio下载文件
	 * @param storeFileName
	 * @param host
	 * @return
	 */
	public static File getStoreFile(String storeFileName,String host) {
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		try {
			String downloadUrl = getDownloadURL(host, storeFileName);
			bis = new BufferedInputStream(getFileInputStream(downloadUrl));
			String path = new File("").getCanonicalPath()+File.separator+storeFileName;
			File file = new File(path);
			fos = new FileOutputStream(file);
            int b = 0;
            byte[] byArr = new byte[1024];
            while ((b=bis.read(byArr))!=-1) {  
            	fos.write(byArr, 0, b);
            }
            return file;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 * 文件删除
	 * @param file
	 */
	public void deleteFile(File file) {
		if(file != null && file.exists()) {
			file.delete();
		}
	}
}
